"""
softmax回归的简洁实现
张量和网络需要手动加载到显存中
"""

import torch
from torch import nn
from d2l import torch as d2l
import os

def init_weights(m):
        if type(m) == nn.Linear:
            nn.init.normal_(m.weight, std=0.01)

if __name__ == '__main__':
    # os.environ["CUDA_VISIBLE_DEVICES"] = "2"
    # torch.cuda.set_device(0)
    batch_size = 256
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

    # PyTorch不会隐式地调整输入的形状。因此，
    # 我们在线性层前定义了展平层（flatten），来调整网络输入的形状
    net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))

    # 网络初始化参数的使用
    net.apply(init_weights)
    net.cuda()
    # net = net.to(device=torch.device('cuda:0'))
    print(net[1].weight.data.device)
    # 交叉熵损失函数
    loss = nn.CrossEntropyLoss(reduction='none')
    # 优化算法
    trainer = torch.optim.SGD(net.parameters(), lr=0.1)
    # 训练
    num_epochs = 20
    d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
    d2l.plt.show()


